package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice//指定拦截那些类型的控制器,将方法的返回值 R 对象转换为json格式的数据, 响应给页面
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlHandle(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知异常");
    }

    @ExceptionHandler(CustomExceotion.class)
    public R<String> CustomExceotionHandle(CustomExceotion ex){
        return R.error(ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> ExceptionHandle(Exception ex){
        return R.error(ex.getMessage());
    }
}
